package com.qiwo.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.qiwo.api.pojo.vo.TokenVO;
import com.qiwo.api.service.AppUserService;
import com.qiwo.api.util.AuthUtil;
import com.qiwo.common.annotation.Log;
import com.qiwo.common.domain.UserInfoDO;
import com.qiwo.common.service.UserService;
import com.qiwo.common.utils.DateUtils;
import com.qiwo.common.utils.Result;
import com.qiwo.common.utils.excel.ExcelUtil;
import com.qiwo.sys.domain.UserDO;
import com.qiwo.webshow.dao.CarDoDao;
import com.qiwo.webshow.domain.CarDo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright
 *
 * @Author:chenwenchao
 * @Date:2018/10/11 0011
 * Description:
 */
@RequestMapping("/api/weichat/")
@Controller
@Api(tags="微信操作模块", description = "微信端操作")
public class ApiWeiChatController {

  @Autowired
  private UserService userService;
  @Autowired
  private AppUserService appUserService;
    @PostMapping("userauth")
    @Log("获取openId跟token")
    @ResponseBody
    @ApiOperation("获取openId跟token")
    public Result<?> refresh(@RequestParam String code) {
       // TokenVO token = userService.refreshToken(uname, refreshToken);
      //  return Result.ok(token);
        if(StringUtils.isBlank(code)){
            return new Result(202,"code获取异常",null);
        }
        System.out.println("code:"+code);
        try {
            //获取code后，请求以下链接获取access_token
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID
                    + "&secret=" + AuthUtil.APPSECRET
                    + "&code=" + code
                    + "&grant_type=authorization_code";
           // String jsonStr="{\"access_token\":\"14_1G4q421ziFAqw9txzeDpTZxCNAHpMM5vkO6Pod5VS-0fAbT7B-qa4UFVVQph64H0bOkOLjh2yTQEPctUYW71VLghxHRuqrSI1I6BX4en7ak\",\"expires_in\":7200,\"refresh_token\":\"14_ezsPHmebwi9ImF29GvWC73zcOtr4Wea7KF76ZlCqH4iDtpklly5DPkoTyAxDohizIKANZutkslCVKOYhCxojpONa_kvM_LGMhOKMq0_P524\",\"openid\":\"oJaHU1bS7ZlTG9N1ZKClVa1DTWLQ\",\"scope\":\"snsapi_base\"}";

            //通过网络请求方法来请求上面这个接口
            JSONObject jsonObject =AuthUtil.doGetJson(url);
                    // JSON.parseObject(jsonStr);AuthUtil.doGetJson(url);

            System.out.println("==========================jsonObject" + jsonObject);
           if(jsonObject==null||jsonObject.get("openid")==null){

                   return new Result(202,"openid获取失败",null);

           }
            //从返回的JSON数据中取出access_token和openid，拉取用户信息时用
            String token = jsonObject.getString("access_token");

            String openid = jsonObject.getString("openid");

            // 第三步：刷新access_token（如果需要）

          /*  // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token
                    + "&openid=" + openid
                    + "&lang=zh_CN";
            //通过网络请求方法来请求上面这个接口
            JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

            System.out.println(userInfo);*/


            //第1种情况：使用微信用户信息直接登录，无需注册和绑定
//        request.setAttribute("info", userInfo);
            //直接跳转
//        request.getRequestDispatcher("/index1.jsp").forward(request, response);


            //第2种情况： 将微信与当前系统的账号进行绑定(需将第1种情况和@WebServlet("/callBack")注释掉)
            //第一步，根据当前openid查询数据库，看是否该账号已经进行绑定
            try {
                //已经绑定
                JSONObject jsonObject1=new JSONObject();
                TokenVO tokenV=new TokenVO();
                UserInfoDO user = userService.findOneByKv("weichatopenid", openid);
                Integer status=200;
                if(user!=null){
                   tokenV=appUserService.getToken(user);
                    tokenV.setOpenId(openid);
                    jsonObject1.put("userInfo",user);
                }else{
                    //未绑定
                    tokenV=new TokenVO();
                    tokenV.setOpenId(openid);
                    status=201;
                }

                jsonObject1.put("token",tokenV);

                return new Result(status,"获取成功",jsonObject1);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }catch (Exception ex){
            ex.printStackTrace();;
        }
        return null;
    }
    @GetMapping("getCarInfo")
    @ResponseBody
    @ApiOperation("获取openId跟token")
    public Result<?> Push(@RequestParam("key") String key,@RequestParam("start") Integer start) {

        getInfo(key,start);
        return Result.ok();
    }

    @Autowired
    private CarDoDao carDoDao;

    public  Integer getInfo(String key,Integer current){

        RestTemplate restTemplate=new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(null, headers);
        Integer num=1;
        try {
            ResponseEntity responseEntity = restTemplate.getForEntity("http://183.62.192.22:64096/vehquery?key=" + key + "&curPage=" + current + "&callback=Clustercallback&_=1541993050427", String.class);
            String data = responseEntity.getBody().toString();
            data = data.replace("Clustercallback(", "").replace(")", "");
            JSONObject object = JSON.parseObject(data);
            Integer totlal = object.getInteger("Total");
            Integer pages = object.getInteger("pages");
            if (totlal != null && totlal > 0) {
                JSONArray rows = object.getJSONArray("Rows");
                for (int i = 0; i < rows.size(); i++) {
                    CarDo carDo = rows.getJSONObject(i).toJavaObject(CarDo.class);
                    try {
                        carDoDao.insert(carDo);
                    } catch (Exception ex) {
                        System.out.println(current);
                    }
                }
                System.out.println(responseEntity.getBody());
                if (current + 1 <= pages) {
                    getInfo(key, current + 1);
                }
            } else {
                System.out.println(current);
            }
        }catch (Exception ex){
            System.out.println(ex.toString()+"数值:"+current);
        }
        return  0;
    }
    @ApiOperation(value = "批量导出汽车信息")
    @GetMapping("/exprotCarInfo")
    public void exprotExcel(HttpServletResponse response) throws Exception {

    }
    @ApiOperation(value = "批量导入信息")
    @RequestMapping(value = "readExcel", method = RequestMethod.POST)
    @ResponseBody
    public Object readExcel(MultipartFile excel) {
        return ExcelUtil.readExcel(excel, new UserDO());
    }



}
